package framework;

import java.util.Calendar;
import java.util.Date;

import org.testng.Reporter;

/**
 * Класс-обертка для поддержки логирования
 * Реализован паттерн синглтон (для доступа из различных классов)
 */
public final class Logger {

    private static final org.apache.log4j.Logger logger
        = org.apache.log4j.Logger.getLogger(Logger.class);
    private static Logger instance = null;
    public static final String LOG_DELIMITER = "::";
    private static long timeStamp = -1;

    private Logger() {
    }

    /**
     * Стандартная реализация паттерна синглтон
     */
    public static synchronized Logger getInstance() {
        if (instance == null) {
            instance = new Logger();
        }
        return instance;
    }

    public void debug(String message) {
        logger.debug(message);
    }

    public void testName(String message) {
        logger.info(String.format(
                "=================  Test: '%1$s' ============= ", message));
        logger.info("-------------------------------------------------------");
    }

    public void step(int step, String message) {
        //Log step execution time
        Date d = new Date();
        if (timeStamp != -1) {
            long testLength = d.getTime() - timeStamp;
            //Stupid hack for preconditions
            if (step == 0) {
                Reporter.log(String.format(
                        "Clean up completed in %1$ds", testLength / 1000));
            } else {
                Reporter.log(String.format(
                        "Completed in %1$ds", testLength / 1000));
            }
        }
        timeStamp = d.getTime();

        logger.info(String.format(
                "--------==[ Step %1$d: %2$s ]==--------", step, message));
        if (step != 0) {
            Reporter.log("</div><br>");
        }
        Reporter.log(String.format(
                "<img src='"
              + "http://www.microsoft.com/global/learning/ru/ru/"
              + "PublishingImages/icon-collapse-plus.gif'"
              + "onClick=\"javascript:toggleElement('step-%1$d', 'block')\"/>"
              + "&nbsp;<span>%2$s</span>",
                step, message));
        Reporter.log(String.format(
                "<div id='step-%1$d' class='testOutput'"
              + "style='display:none; margin-left: 30px'>", step));
    }

    public void info(String message) {
        logger.info(message);
        Reporter.log(String.format(
                "%1$tT %2$s", Calendar.getInstance(), message));
    }

    public void warn(String message) {
        logger.warn(message);
        Reporter.log(message);
    }

    public void error(String message) {
        logger.error(message);
        Reporter.log(message);
    }

    public void fatal(String message) {
        logger.fatal(message);
        Reporter.log(message);
    }
}
